#include<Util/omscodehelper.h>
#include<QFile>
#include<qdebug.h>
#include<Util/handlefile.h>
#include<QFileDialog>
#include<QProcess>
omsCodeHelper::omsCodeHelper(){

}

//init
bool omsCodeHelper::init(QWidget *Widget,QString packageName, QString dirPath, QString simName, QString inputFileName, QString outputFileName,QString JAVAHOME){
    if(Widget==NULL||
           packageName==""||
            dirPath==""||
            simName==""||
            inputFileName==""||
            outputFileName==""
           ) {
        return false;
    }
    this->widget=Widget;
    this->DirPath=dirPath;
    this->packageName=packageName;
    this->simName=simName;
    this->inputFileName=inputFileName;
    this->outputFileName=outputFileName;
    javaHome="\""+JAVAHOME+"\"";

    return true;
}

//Fix Main.java
bool  omsCodeHelper::readMain(){
    QFile file(this->DirPath+"\\templates\\templateFiles\\OMS\\Main.java");
    if(!file.open(QIODevice::ReadWrite | QIODevice::Text)){
        qWarning()<<this->DirPath<<endl;
        qWarning()<<"Failed to open Main.java."<<endl;
        return false;
    }
    QString str(file.readAll());
    file.close();

    str.replace("${simName}","\""+simName+"\"");

    str.replace("${InputFileName}","\""+inputFileName+"\"");

    QString udxStr="";
    udxStr.append("if (!RsUdxHelper.udx2RsBSQ(udxDataset, saveTmpPath,PathUtil.getPath(Main.class))) { \n");
    udxStr.append("             System.out.println(\"save bsq file failed.\");\n");
    udxStr.append("     return;\n");
    udxStr.append(" }");
    str.replace("${udx2RsBSQ}",udxStr);

    str.replace("${outputFileName}","\""+outputFileName+"\"");

    QString img2Udx="";
    img2Udx.append("udx_return_Dt = ImageUdxHelper.img2Udx(resultPath, PathUtil.getPath(Main.class));\n");
    str.replace("${img2Udx}",img2Udx);

    //保存文件
    if(!str.isNull()&&this->saveFile(DirPath+"\\java\\Main.java",str)){
        return true;
    }
    else {
        qWarning()<<"Code generation error."<<endl;
        return false;
    }

}


//Fix PathUtil.java
//bool omsCodeHelper::readPathUtil(){
//    QFile file(this->DirPath+"\\templates\\templateFiles\\OMS\\PathUtil.java");
//    if(!file.open(QIODevice::ReadWrite | QIODevice::Text)){
//        qWarning()<<"Failed to open PathUtil.java"<<endl;
//        return false;
//    }
//    QString str(file.readAll());
//    file.close();
//    return str;
//}

//Fix Utils.java
bool omsCodeHelper::readUtils(){
    QFile file(this->DirPath+"\\templates\\templateFiles\\OMS\\Utils.java");
    if(!file.open(QIODevice::ReadWrite | QIODevice::Text)){
        qWarning()<<"Failed to open Utils.java"<<endl;
        return false;
    }
    QString str(file.readAll());
    file.close();

    if(!str.isNull()&& this->saveFile(DirPath+"\\java\\Utils.java",str)){
        return true;
    }
    else{
        qWarning()<<"Code generation error."<<endl;
        return false;
    }

}

//Fix MANIFEST.MF
bool omsCodeHelper::readManifest(){
    QFile file(this->DirPath+"\\templates\\templateFiles\\OMS\\MANIFEST.MF");
    if(!file.open(QIODevice::ReadWrite | QIODevice::Text)){
        qWarning()<<"Failed to open MANIFEST.MF"<<endl;
        return false;
    }
    QString str(file.readAll());
    file.close();

    if(!str.isNull()&& this->saveFile(DirPath+"\\java\\MANIFEST.MF",str)){
        return true;
    }
    else {
        qWarning()<<"Code generation error."<<endl;
        return false;
    }
}

//Fix compile.bat
bool omsCodeHelper::readCompile(){
    QFile file(this->DirPath+"\\templates\\templateFiles\\OMS\\compile.bat");
    if(!file.open(QIODevice::ReadWrite | QIODevice::Text)){
        qWarning()<<"Failed to open compile.bat"<<endl;
        return false;
    }
    QString str(file.readAll());
    file.close();
    QString str1=this->DirPath;
    str.replace("${dirPath}",str1.replace("/","\\"));
    str.replace("${JAVAHOME}",javaHome);
      if(!str.isNull()&&this->saveFile(DirPath+"\\java\\compile.bat",str)){
          return true;

      }else{
          qWarning()<<"conpile.bat Fix error."<<endl;
          return false;
      }
}

bool omsCodeHelper::getLicense(QString AreaText){
    if(!AreaText.isNull()&&this->saveFile(DirPath+"\\omsWraper\\license.txt",AreaText)){
        return true;
    }else{
        qWarning()<<"license.txt fix error."<<endl;
        return false;
    }
    return true;

}

bool omsCodeHelper::omsCompile(){
    char*  ch;
    QByteArray ba = (DirPath+"\\java\\compile.bat").toLatin1();
    if(ba.isNull()){
        return false;
    }
    ch=ba.data();
    system(ch);
    qDebug() << "code generate sucess." <<endl;
    return true;
}


int omsCodeHelper::omsPackage(){
    QString fileName = QFileDialog::getSaveFileName(widget,
           QObject::tr("Open Config"),
            "",
            QObject::tr("Zip Files (*.zip)"));


        QString winRARPath = "\""+this->DirPath+"\\templates\\winrar\\WinRAR.exe"+"\"";
        QString ZipPath = "\""+fileName+"\"";
        QString SrcFoldPath = "\""+this->DirPath+"\\omsWraper\\"+"\"";
        QString commandStr = (winRARPath+" a -ep1 -r -m3 -ibck "+ZipPath+" "+SrcFoldPath);

        QProcess p(0);
        p.start(commandStr);
        p.waitForStarted();
        p.waitForFinished();
        qWarning()<<QString::fromLocal8Bit(p.readAllStandardError())<<endl;

            //删除临时文件，临时文件夹
            if(DelDir(DirPath+"/OMSTemp")&& DelDir(DirPath+"/java")&& DelDir(DirPath+"/omsWraper")){
                qWarning()<<"Delete the fold successfully."<<endl;
            }else{
                qWarning()<<"Failed to delete the fold."<<endl;
                return 0;
            }
      return 1;

}

//Save File

bool  omsCodeHelper::saveFile(QString filename,QString& str){
    QFile file(filename);

    if(!file.open(QIODevice::ReadWrite | QIODevice::Text))
    {
        qWarning()<<"error : failed to save file.\n";
        return false;
    }
    QTextStream in(&file);
    in << str;
    in.flush();
    file.close();
    return true;
}

